<template>
    <ElContainer class="admin-container">
        <el-header class="row" height="40px">
            <div class="col-3">
                <el-button type="primary" @click="created">添加</el-button>
            </div>
        </el-header>
        <el-main class="admin-main">
            <el-table :data="tableData" border height="100%" @sort-change="sortchange">
                <el-table-column prop="ID" sortable="custom" width="80px" label="ID"></el-table-column>
                <el-table-column prop="name" label="名称"></el-table-column>
                <el-table-column prop="num" label="每人最多兑换数量" width="220"></el-table-column>
                <el-table-column prop="integral" label="金币" sortable="custom" width="120"></el-table-column>
                <el-table-column prop="remainingquantity" label="库存数量" width="120"></el-table-column>
                <el-table-column prop="createdAt" sortable="custom" label="创建时间" width="160"
                    :formatter="(row) => TimeYH(row.createdAt)"></el-table-column>
                <el-table-column prop="createdAt" label="操作" width="240">
                    <template #default="scope">
                        <el-button type="primary"
                            @click="$router.push({ name: '金币兑换人', params: { ID: scope.row.ID } })">兑换人
                        </el-button>
                        <el-button type="warning" @click="update(scope.row)">修改
                        </el-button>
                        <el-button type="danger" @click="del(scope.row)">{{ scope.row.offshelf ? '下架' : '上架'
                            }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
        <el-footer>
            <el-pagination @current-change="handleCurrentChange" :page-size="Number(limit)" layout="prev, pager, next"
                :total="count"></el-pagination>
        </el-footer>
        <el-dialog v-model="dialogVisible" title="添加" width="800px" destroy-on-close>
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
                status-icon>

                <el-form-item label="名称" prop="name">
                    <el-input v-model="ruleForm.name" />
                </el-form-item>
                <el-form-item label="金币" prop="integral">
                    <el-input-number v-model="ruleForm.integral" :min="1" :max="999" />
                </el-form-item>
                <el-form-item label="每人最多兑换数量" prop="num">
                    <el-input-number v-model="ruleForm.num" :min="1" :max="999" />
                </el-form-item>
                <el-form-item label="库存数量" prop="remainingquantity">
                    <el-input-number v-model="ruleForm.remainingquantity" :min="1" :max="999999" />
                </el-form-item>
                <el-form-item label="是否上架" prop="remainingquantity">
                    <el-radio-group v-model="ruleForm.offshelf" class="ml-4">
                        <el-radio :label="true">上架</el-radio>
                        <el-radio :label="false">下架</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="产品图片" prop="remainingquantity">
                    <el-upload class="avatar-uploader" :show-file-list="false" accept=".png,.svg,.jpg"
                        :http-request="request" :limit="1">
                        <img v-if="ruleForm.image" :src="ruleForm.image" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="产品详情" prop="context">
                    <Wangeditor id="Wangeditor" :value="applicationcontext" ref="contexteditor2" :zIndex="2">
                    </Wangeditor>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="resetForm(ruleFormRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </ElContainer>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue';
import { ElButton, ElContainer, ElFooter, ElHeader, ElIcon, ElInput, ElMain, ElMessage, ElMessageBox, ElPagination, ElTable, ElTableColumn, FormInstance, FormRules } from "element-plus";
import { assign, forEach } from 'lodash-es';
import {
    onMounted,
    reactive,
    ref,
    watch
} from "vue";
import { Iobj, asynccreateintegralreward, asyncgetintegralreward } from "../../../api";
import Wangeditor from "../../../components/wangeditor.vue";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { TimeYH } from "../../../util/time";
import updateoss from "../../../util/updateoss";
const dialogVisible = ref(false)
const ruleForm = reactive<Studycodemodel.Iintegralreward>({})
const formquery = reactive<Studycodemodel.Iintegralreward>({})
const sortable = ref<"DESC" | "ASC">("DESC");
const limit = ref(20);
const offset = ref(0);
const order = ref<keyof Studycodemodel.Iintegralreward>("ID");

const contexteditor2 = ref()
const applicationcontext = ref('')

const rules = reactive<FormRules>({
    name: [
        { required: true, trigger: 'change' },
    ],
    remainingquantity: [
        { required: true, trigger: 'change' },
    ],
    num: [
        { required: true, trigger: 'blur' },
    ],
    integral: [
        { required: true, trigger: 'blur' },
    ],
})

const tableData = ref<Studycodemodel.Iintegralreward[]>([]);

const ruleFormRef = ref<FormInstance>()

function created() {
    for (const i in ruleForm) {
        delete ruleForm[i]
    }
    dialogVisible.value = true
    applicationcontext.value = '';
}

function update(row: Studycodemodel.Iintegralreward) {

    dialogVisible.value = true; Object.assign(ruleForm, assign({}, row));
    applicationcontext.value = row.context || '';
}

const count = ref<number>(0);

onMounted(() => {
    start()
});

async function request(file: { file: File }) {
    const { name } = await updateoss([file.file]);
    ruleForm.image = `https://cdn.hterobot.com/${name}`;
}


async function resetForm(formEl?: FormInstance) {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            ruleForm.context = contexteditor2.value?.gethtml();;

            asynccreateintegralreward(ruleForm).then(e => {
                forEach(ruleForm, (e, k) => {
                    delete ruleForm[k]
                })
                dialogVisible.value = false
                start()
            })
        }
    })
}

async function start() {
    try {
        const obj: Iobj<Studycodemodel.Iintegralreward> = {
            _limit: limit.value,
            _offset: offset.value,
            _order: order.value,
            _sortable: sortable.value,
            ...formquery
        }
        const data = await asyncgetintegralreward(obj)
        tableData.value = data.rows
        count.value = data.count
    } catch (e: any) {

        ElMessage.error(e);
    }
}




function handleCurrentChange(val: number) {
    offset.value = limit.value * (val - 1);
}

function sortchange(row: {
    order: string;
    prop: keyof Studycodemodel.Iintegralreward;
}) {
    const { prop } = row;
    if (row.order == "descending") {
        sortable.value = "DESC";
    } else {
        sortable.value = "ASC";
    }
    order.value = prop;
}


function del(row: Studycodemodel.Iintegralreward) {
    try {
        ElMessageBox.confirm(`是否${!row.offshelf ? '上架' : '下架'}?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(async () => {
                await asynccreateintegralreward({ ID: row.ID, offshelf: !row.offshelf });
                ElMessage({
                    type: "success",
                    message: "成功!",
                });
                start();
            })
            .catch((e: string) => {
                ElMessage({
                    message: "失败" + e,
                    type: "error",
                });
            });
    } catch (e: any) {
        ElMessage({
            type: "info",
            message: "已取消",
        });
    }
}


watch([limit, offset, order, sortable], () => {
    start();
});
</script>

<style scoped>
a {
    text-decoration: none;
}

.avatar {
    width: 178px;
    height: 178px;
}

.avatar-uploader .el-upload {
    border: 1px dashed #000;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
